package com.cloudboy.redisConsole.spring;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;

import com.cloudboy.redisConsole.model2.MyRedisData;
import com.cloudboy.redisConsole.model2.MyRedisDatabase;
import com.cloudboy.redisConsole.model2.MyRedisKeyValue;
import com.thoughtworks.xstream.XStream;

@SpringBootApplication
public class App implements CommandLineRunner {

	private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
	private static XStream xs = new XStream();
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	private void test() {
		LOGGER.info("testing is started.");
		MyRedisData redisData = new MyRedisData();
		MyRedisDatabase redisDatabase = new MyRedisDatabase();
		redisData.addDatabase(redisDatabase);
		Set<String> keys =  redisTemplate.keys("*");
		for(String key : keys) {
			MyRedisKeyValue keyValue = new MyRedisKeyValue();
			DataType type = redisTemplate.type(key);
			keyValue.setType(type.code());
			keyValue.setKey(key);
			if(type.equals(DataType.HASH)) {
				keyValue.setHashValue(redisTemplate.boundHashOps(key).entries());
			} else if(type.equals(DataType.STRING)) {
				keyValue.setStringValue(redisTemplate.boundValueOps(key).get().toString());
			}
			redisDatabase.addKeyValue(keyValue);
		}
		LOGGER.info(xs.toXML(redisData));
	}

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		this.test();
	}
}
